package com.whl.sm.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Producer;
import com.whl.sm.common.result.Result;
import com.whl.sm.controller.BaseController;
import com.whl.sm.dto.LoginDto;
import com.whl.sm.model.system.OrgUser;
import com.whl.sm.model.system.OrgUserInfo;
import com.whl.sm.service.system.OrgUserInfoService;
import com.whl.sm.service.system.OrgUserService;
import com.whl.sm.shiro.JwtUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.ibatis.executor.loader.ResultLoaderMap;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sys-admin")
public class LoginController extends BaseController {

    @Autowired
    private Producer producer;

    @Autowired
    private OrgUserService orgUserService;

    @Autowired
    private OrgUserInfoService orgUserInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequiresAuthentication
    @RequestMapping("/success")
    public Result loginSuccess(){
        return Result.ok();
    }

    @RequestMapping("/fail")
    public Result accessFail(){
        return Result.build(401,"拒绝访问，请登录!");
    }


    @RequestMapping("/login")
    public Result login(@RequestParam("account") String account,
                        @RequestParam("password") String password,
                        @RequestParam(value = "captchaKey",required = false) String captchaKey,
                        HttpServletRequest request) {

        if (Objects.nonNull(captchaKey)){
            if (!redisTemplate.hasKey(captchaKey)){
                return Result.build(444,"验证码已过期，请重新获取!");
            }
            String code = request.getParameter("code");
            String identifyCode = String.valueOf(redisTemplate.opsForValue().get(captchaKey));
            if (!identifyCode.equals(code)){
                return Result.build(444,"验证码错误");
            }
        }
        List<OrgUser> orgUsers = orgUserService.list(new QueryWrapper<OrgUser>()
                .eq("account",account)
                .eq("password",password)
        );
        OrgUser userBean = orgUsers.size()>0?orgUsers.get(0):null;
        if (Objects.nonNull(userBean)){
            LoginDto resultInfo = new LoginDto();
            OrgUserInfo userBeanInfo = orgUserInfoService.getByUserId(userBean.getId());
            if (Objects.nonNull(userBeanInfo)){
                resultInfo.setAvatar(userBeanInfo.getAvatar());
                resultInfo.setUserName(userBeanInfo.getUserName());
            }
            String resultToken = JwtUtils.sign(userBean.getId(),userBean.getLoginName(), userBean.getPassword());
            resultInfo.setAccount(userBean.getAccount());
            resultInfo.setLoginName(userBean.getLoginName());
            resultInfo.setToken(resultToken);
            return Result.ok(resultInfo);
        } else {
            return Result.build(444,"登录失败，请检查登录信息！");
        }
    }

    @RequestMapping("/captcha")
    public Result captcha() throws IOException {

        String key = UUID.randomUUID().toString();
        String code = producer.createText();

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Image = str + encoder.encode(outputStream.toByteArray());

        redisTemplate.opsForValue().set(key,code,120, TimeUnit.SECONDS);

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("key",key);
        resultMap.put("base64Image",base64Image);

        return Result.ok(resultMap);
    }


}
